package com.hare.auth.filter;

import com.alibaba.fastjson.JSON;


import com.hare.auth.base.BaseLoginUser;
import com.hare.common.global.constant.BaseConstant;
import com.hare.common_redis.RedisCache;
import com.hare.auth.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;


import java.io.IOException;

/**
 * @program: Hare
 * @description: 过滤器
 * @author: Hare
 * @create: 2022-06-27 15:45
 * @Version 6.0.1
 **/
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private RedisCache redisCache;

    private JwtUtils jwtUtils;


    public JwtAuthenticationTokenFilter(RedisCache redisCache, JwtUtils jwtUtils) {
        this.redisCache = redisCache;
        this.jwtUtils = jwtUtils;
    }

    /**
     * token效验处理
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //获取AUTHORIZATION信息
        String headerAuth = request.getHeader(BaseConstant.AUTHORIZATION);

        //判断是否携带token
        if (!StringUtils.hasText(headerAuth)) {
            filterChain.doFilter(request, response);
            return;
        }
        //查询此token是否过期
        if (StringUtils.hasText(headerAuth) && headerAuth.startsWith(BaseConstant.BEARER)) {
            String token = headerAuth.substring(BaseConstant.BEARER.length());
            String realToken = BaseConstant.PREFIX_TOKEN + token;
            boolean isFlag = redisCache.hasKey(realToken);
            if (!isFlag) {
                filterChain.doFilter(request, response);
                return;
            } else {
                //刷新token
                jwtUtils.refreshJwtTime(realToken);
                //解析token
                BaseLoginUser sysAdmin = JSON.parseObject(redisCache.getCacheObject(realToken).toString(), BaseLoginUser.class);
                //放入springsecurity上下文
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(sysAdmin, null, sysAdmin.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                filterChain.doFilter(request, response);
            }
        }
    }
}
